package controller;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.QuestionModel;
import model.TagModel;
import util.CacheHandle;
import entity.Question;
import entity.Tag;

/**
 * Servlet implementation class TagDetail
 */
@WebServlet("/TagDetail")
public class TagDetail extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
			
		// Language
		HttpSession session = request.getSession(true);
		String lang = "";
		ResourceBundle resource = null;
		if (session.getAttribute("language") != null) {
			resource = (ResourceBundle) session.getAttribute("language");
			lang = resource.getString("code");

		} else {
			resource = ResourceBundle.getBundle("en", new Locale("en"));
			session.setAttribute("language", resource);
			lang = "en";
		}

		// Paginate
		int currentPage = 0;
		String path = ((HttpServletRequest) request).getRequestURI();
		String[] splittedURI = path.split("/");
		if (splittedURI.length == 5) {
			currentPage = Integer.valueOf(splittedURI[4]);
		}

		// Property handle		
		request.setAttribute("title", resource.getString("title"));
		request.setAttribute("keyword", resource.getString("keyword"));
		request.setAttribute("description", resource.getString("description"));

		// Get alias from uri		
		String alias = splittedURI[3];		
		TagModel tagModel = new TagModel();		
		
		// Add cache
		if (splittedURI.length == 4) {
			Tag addCache = tagModel.find(alias);
			if (addCache!=null) {				
				CacheHandle.setTagCache(alias);
			}	
		}			

		// Return view
		QuestionModel questionModel = new QuestionModel();
		List<Question> listQuestion = questionModel.findByTag(alias, lang, currentPage);

		if (listQuestion.size() > 0) {
			request.setAttribute("currentPage", currentPage);
			request.setAttribute("listQuestionTag", listQuestion);
			request.setAttribute("tagAlias", alias);
			request.getRequestDispatcher("/tag_detail.jsp").forward(request,
					response);
		} else {
			if (currentPage == 0) {
				response.sendRedirect("/index");
			} else {
				listQuestion = questionModel.findByTag(alias, lang, 0);
				request.setAttribute("currentPage", 0);
				request.setAttribute("listQuestionTag", listQuestion);
				request.setAttribute("tagAlias", alias);
				request.getRequestDispatcher("/tag_detail.jsp").forward(request,
						response);
			}
		}
	}

}
